package com.shop.servlet.impl;

import com.shop.dao.UserDao;
import com.shop.dao.impl.UserDaoImpl;
import com.shop.dto.Email;
import com.shop.entity.User;
import com.shop.servlet.UserServlet;
import com.shop.tools.MessageTool;
import org.mindrot.jbcrypt.BCrypt;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * com.shop.servlet.impl文档说明
 *
 * @author Angluzha
 * @version 2022/9/13
 */
public class UserServletImpl extends BaseServletImpl<User> implements UserServlet{
    {
        dao = new UserDaoImpl();
    }

    @Override
    public boolean verification(User user) {
        try {
                UserDao dao = (UserDao) this.dao;
                user.setPassword(BCrypt.hashpw(user.getPassword(),BCrypt.gensalt()));
                user.setUuid(UUID.randomUUID().toString().replace("-",""));
                if (dao.insert(user)) {//
                    Email email = new Email();
                    email.setAddressee(user.getEmail());
                    email.setTitle("2205电商项目新用户激活");
                    email.setContentText("欢迎成为我们系统的会员，<a href ='http://localhost:8080/user/registerActiveUser?code="+user.getUuid()+"'>点击这里激活</a>");
                    MessageTool.sendEmail(email);
                    return true;
                }
            } catch (Exception e){
                e.printStackTrace();
            }
        return false;
    }

    @Override
    public boolean activation(String code) {
        try {
            if (code==null||"".equals(code))
                return false;
            UserDao dao = (UserDao) this.dao;
            return dao.exist(code)?false:dao.activation(code);
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public Map<String, Object> login(User user) {
        String password = user.getPassword();
        Map<String,Object> map = new HashMap<>();
        map.put("code",100);
        try {
            user = (User) dao.selectOne(user);
            if (user==null){
                map.put("msg","账号密码错误");
                return map;
            }
            if (user.getStatus()==0){
                map.put("msg","账号未激活");
                return map;
            }
            if (!BCrypt.checkpw(password,user.getPassword())){
                map.put("msg","账号密码错误");
            }else{
                user.setPassword(null);
                map.put("code",200);
                map.put("msg","登录成功");
                map.put("user",user);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return map;
    }
}
